package com.wbp.cms.web.controller.admin;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.wbp.cms.client.common.domain.OrganizationDO;
import com.wbp.cms.client.common.query.OrganizationQuery;
import com.wbp.cms.client.common.service.OrganizationService;
import com.wbp.cms.client.result.Result;
import com.wbp.cms.client.user.domain.UserDO;
import com.wbp.cms.client.user.query.UserQuery;
import com.wbp.cms.client.user.service.UserService;
import com.wbp.cms.client.util.JsonUtils;
import com.wbp.cms.web.controller.BaseController;


/**
 * 组织机构管理
 * @Description: 
 * @Department:
 * @author andy.lhc
 * @date 2016年3月10日 下午4:55:09 
 */
@Controller("organizationMgrController")
@RequestMapping("/orgmgr")
public class OrganizationMgrController  extends BaseController{

   @Resource
   private OrganizationService   organizationService ;
  
   private static final Logger  logger = Logger.getLogger(OrganizationMgrController.class) ;
   
   @Resource
   private  UserService  userService ;
   
   
   /**
    * 进入页面时的方法
    * @return
    */
   @RequestMapping("/tolist")
   public ModelAndView  toList(){
     ModelAndView mv = new ModelAndView();
     mv.setViewName("admin/organization/organizationList"); 
     return mv ;
   }
   
   /**
    * 显示一个组织机构树
    * @param pageNo
    * @param pageSize
    * @return
    */
   @RequestMapping(value="/getorg", produces = "application/json;charset=UTF-8")
   @ResponseBody
   public String doList(@RequestParam(value="id",defaultValue="0",required=true) Long id) {
 
     OrganizationQuery  organizationQuery =new OrganizationQuery();
     List<OrganizationDO> list = null ;
     organizationQuery.setParentId(id);
     list  = this.organizationService.queryOrganization(organizationQuery) ;
     /*if(id == 0){
       list  = this.organizationService.queryOrganization(organizationQuery) ;
     }else{
          
          list = this.organizationService.queryOrganization(organizationQuery) ; // queryChildOrganizations(pId) ;
     }*/
     if(list ==null){
        list = Lists.newArrayList() ;
        OrganizationDO org =new OrganizationDO();
        org.setId(0L);
        org.setName("无部门");
        org.setParentId(0L); 
        org.setIcon("");
     }
     return new Gson().toJson(getOrgTreeNode(list));
   }
   
   private  List<Map<String,Object>> getOrgTreeNode(List<OrganizationDO> orgList){
     List<Map<String,Object>>  list =Lists.newArrayList() ;
     for(OrganizationDO org: orgList){
          Map<String,Object>  map = Maps.newTreeMap() ;
          map.put("id", org.getId()) ;
          map.put("pId", org.getParentId()) ;
         //  map.put("icon", org.getIcon()) ;
          map.put("name", org.getName()) ;
          OrganizationQuery  orgQuery =new OrganizationQuery();
          orgQuery.setParentId(org.getId());
          int count = this.organizationService.queryOrganizationCount(orgQuery) ;
          if(count > 0)
             map.put("isParent",true) ;
          else 
             map.put("isParent",false) ;
          /*if(org.getParentId().longValue() == 0){
             map.put("open", true) ;
             map.put("isParent", true) ;
          }*/
          list.add(map) ;
     }
     
     return list ;
   }
   
   /**
    * to 增加子组织机构 页面 
    * @param orgId
    * @return
    */
   @RequestMapping("/toedit")
   public ModelAndView  toEdit(@RequestParam(value="orgId",required=true,defaultValue="0") Long orgId,
                              @RequestParam(value="type",required=true,defaultValue="")  String type ){
     ModelAndView mv = new ModelAndView();
     mv.setViewName("admin/organization/organizationEdit"); 
     Result<OrganizationDO>  orgResult = this.organizationService.queryOrganizationById(orgId) ;
     if(orgResult.isSuccess() && orgResult.getData() != null ){
        mv.addObject("org", orgResult.getData()) ;
     }
     
     mv.addObject("type", type) ;
     return mv ;
   }
   
   /**
    *新增，修改组织机构的名称
    * @param request
    * @return
    */
   @RequestMapping(value="/doedit", produces = "application/json;charset=UTF-8")
   @ResponseBody
   public String  doEdit(HttpServletRequest request  ){
     try{
       
       OrganizationDO org = this.getRequestObject(request, OrganizationDO.class) ;
       
       if(org == null)
           return new Gson().toJson(Result.buildError("org不能为空")) ;
        
       if(StringUtils.isEmpty(org.getName()))
           return new Gson().toJson(Result.buildError("org.Name不能为空")) ;
       
       if(org.getId()==null || org.getId() <=0){
         // 新增  
         OrganizationDO  newOrg = new OrganizationDO();
         newOrg.setName(org.getName());
         newOrg.setStatus(1); // 正常 
         newOrg.setParentId(org.getParentId()); 
         Result<Long>  r1 = this.organizationService.addOrganization(newOrg) ;
         if(r1.isFailed())
            r1.setErrMsg("名称重复,请重新填写!") ;
         return new Gson().toJson( r1 ) ;
       }else if(org.getId() > 0){
         Result<OrganizationDO>  r = this.organizationService.queryOrganizationById(org.getId()) ;
         if(r.isFailed() )
           return new Gson().toJson( Result.buildError("请重新刷新页面"));
         OrganizationDO  editOrg = r.getData() ;
         editOrg.setName(org.getName());
         Result<Boolean> r2 = this.organizationService.modifyOrganization(editOrg);
         if(r2.isFailed())
           r2.setErrMsg("名称重复,请重新填写!") ;
         return new Gson().toJson( r2 )  ;
         
       }
       
       return new Gson().toJson(Result.buildError("请重新刷新页面")) ;
     }catch(Throwable e){
       logger.error("doAdd error:",e);
       return new Gson().toJson(Result.buildError("增加子组强机构失败")) ;
     }
   }
   
   /**
    * 新增，修改组织机构的名称
    * @param request
    * @return
    */
   /*@RequestMapping(value="/doedit", produces = "application/json;charset=UTF-8")
   @ResponseBody
   public String  doEditName(@RequestParam(value="orgId",required=true,defaultValue="0") Long orgId,
                              @RequestParam(value="name",required=true,defaultValue="") String name  ){
     
     if(orgId == null || orgId <=0)
          return new Gson().toJson(Result.buildError("orgId不能为空,应>0")) ;
     if(StringUtils.isEmpty(name))
          return new Gson().toJson(Result.buildError("name不能为空")) ;
     Result<OrganizationDO> r = this.organizationService.queryOrganizationById(orgId) ;
     if(r.isFailed())
          return new Gson().toJson(Result.buildError("orgId:"+orgId+",没有查到对应的组织机构,请检查")) ;
     if(r.isSuccess() && !r.getData().getName().equals(name)){
       OrganizationDO org =r.getData() ;
       org.setName(name);
       return JsonUtils.toJson( this.organizationService.modifyOrganization(org) );
     }
     return JsonUtils.toJson(Result.buildSuccess(true) ) ; // 相等不要修改直接返回 
   }*/
   
   /**
    * 删除组织机构及其下的所有用户之间的关系，小心使用 ，
    * 后面再加权限，要有权限才能使用。
    * @param orgId
    * @return
    */
   @RequestMapping(value="/dodelete", produces = "application/json;charset=UTF-8")
   @ResponseBody
   public String  doDelete(@RequestParam(value="orgId",required=true,defaultValue="0") Long orgId ){
     if(orgId == null || orgId <=0)
         return JsonUtils.toJson(Result.buildError("orgId不能为空,应>0")) ;
     
    // this.organizationService.
     
     return JsonUtils.toJson(Result.buildSuccess(true) ) ; 
   }
   
   /**
    * 通过Org查询下面的所有用户 
    * 把orgid作为表单提交过来
    * @param orgId
    * @return
    */
   @RequestMapping(value="/getorgusers",produces = "application/json;charset=UTF-8")
   @ResponseBody
   public String  doGetOrgUsers(HttpServletRequest request,
                      @RequestParam(value="orgId",required=true,defaultValue="0") Long orgId){
      Map<String,String> maps = this.getParameters(request) ;
     //  System.out.println("doGetOrgUsers---orgId:"+maps.get("orgId")+",requestparams orgId:"+orgId);
     
      Result<List<UserDO>> result =null ;
      if(orgId == null || orgId <=0)
        result = Result.buildSuccess(null) ;
      else{
        UserQuery  userQuery =new UserQuery();
        userQuery.setOrganizationId(orgId);
        result = userService.queryUsers(userQuery) ;
      }
       //  result = userService.queryUsersByOrgId(orgId) ;
      
      return new Gson().toJson(getDataTableMapData(result,maps.get(DT_KEY_DRAW) )) ;
   }
   
   /**
    * 把用户从组织机构中移除，要提示用户，被移除的用户加入到一个组织中
    * @param orgId
    * @param userId
    * @return
    */
   @RequestMapping("/removeorguser")
   @ResponseBody
   public String  doRemoveOrgUser(@RequestParam(value="orgId",required=true,defaultValue="0") Long orgId ,
                               @RequestParam(value="userId",required=true,defaultValue="0") Long userId ){
     
      if(orgId <=0)
          return new Gson().toJson(Result.buildError("orgId:"+orgId+",应>0"));
      if(userId <=0)
          return new Gson().toJson(Result.buildError("userId:"+userId+",应>0"));
      
      UserDO userDO =new UserDO();
      userDO.setId(userId);
      userDO.setOrganizationId(0L);
      Result<Boolean> result = this.userService.modifyUser(userDO) ;
      
      return new Gson().toJson(result);
   }
   
   
   /**
    * 向组织机构中加一个用户
    * @param orgId
    * @param userId
    * @return
    */
   @RequestMapping("/addorguser")
   @ResponseBody
   public String  doAddOrgUser(@RequestParam(value="orgId",required=true,defaultValue="0") Long orgId ,
                               @RequestParam(value="userId",required=true,defaultValue="0") Long userId ){
     
      return new Gson().toJson("");
   }
   
   
   /**
    * 查出不是当前orgId下的所有用户，可以加到此OrgId中来。
    * @param orgId
    * @param userId
    * @return
    */
   @RequestMapping("/getnoorguser")
   @ResponseBody
   public String  getNoOrgUsers(@RequestParam(value="orgId",required=true,defaultValue="0") Long orgId ){

    return new Gson().toJson("");
    }
   
   
}
